<?

class Qi_Util_Lock
{
	private $lock_file = ".lock";
	private $lock_file_path = ".lock";

	public function __construct()
	{
		$this->lock_file_path = $this->lock_file_path();
	}

	public function lock($time = 60)
	{
		if ($this->is_locked($time)) return false;
		file_put_contents($this->lock_file_path, "");
		register_shutdown_function($this->shutdown_function());
		return true;
	}

	public function is_locked($time = 60)
	{
		if ( ! file_exists($this->lock_file_path) ) return false;
		return filemtime($this->lock_file_path) >= time() - $time;
	}

	private function lock_file_path()
	{
		$base = basename($this->lock_file);
		return $base == $this->lock_file
				? getcwd().DIRECTORY_SEPARATOR.$base
				: $base;
	}

	private function shutdown_function()
	{
		$lock_file = $this->lock_file_path;
		$body = <<<F
		\$lock_file = "$lock_file";
		if ( file_exists(\$lock_file) )
			unlink(\$lock_file);
F;
		return create_function("", $body);
	}
}

?>